package com.spring.shopping.service.impl;

import com.spring.shopping.entity.*;
import com.spring.shopping.mapper.OrderItemMapper;
import com.spring.shopping.mapper.OrderMapper;
import com.spring.shopping.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/*
 * @Coding By ZTK:
 */


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public List<Order> getOrdersByUserId(Integer userId, int offset, int size) {
        return orderMapper.selectOrdersByUserId(userId, offset, size);
    }

    @Override
    public int countOrdersByUserId(Integer userId) {
        return orderMapper.countOrdersByUserId(userId);
    }

    @Override
    public void updateOrderStatus(Integer orderId, String status) {
        orderMapper.updateOrderStatus(orderId, status);
    }

    @Override
    public Order createOrder(Integer userId, List<CartItem> cartItems,
                             String receiverName, String receiverAddress, String receiverPhone) {
        BigDecimal totalAmount = BigDecimal.ZERO;

        for (CartItem item : cartItems) {

            BigDecimal itemTotal = BigDecimal.valueOf(item.getProduct().getPrice()).multiply(BigDecimal.valueOf(item.getQuantity()));
            totalAmount = totalAmount.add(itemTotal);
        }

        Order order = new Order();
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setStatus("待支付");
        order.setReceiverName(receiverName);
        order.setReceiverAddress(receiverAddress);
        order.setReceiverPhone(receiverPhone);
        order.setCreatedTime(new Date());

        orderMapper.insertOrder(order);

        for (CartItem item : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(item.getProduct().getId());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setPrice(item.getProduct().getPrice());
            orderItemMapper.insertOrderItem(orderItem);
        }

        return order;
    }

    @Override
    public Order getOrderById(Integer id) {
        Order order = orderMapper.selectOrderById(id);
        if (order != null) {
            List<OrderItem> orderItems = orderItemMapper.selectOrderItemsByOrderId(id);
            order.setOrderItems(orderItems);
        }
        return order;
    }
}